package 多线程.练习.callablePracticePool;

import java.util.concurrent.Callable;
import java.util.concurrent.*;

public class CallablePracticePool {
    // 利用线程池实现 计算 1 + 2 + ... + 1000 的结果

    //Callable 内部类
    static class MyCallable implements Callable<Integer> {
        int start;
        int end;

        public MyCallable(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        // 线程未来任务数组
        Future<Integer>[] futures = new Future[10];

        int sum = 0;
        for (int i = 0; i < 10; i++) {
            int start = i * 100 + 1;
            int end = (i + 1) * 100 + 1;

            // 将 Callable 传入 submit 中, 返回 future 类型
            futures[i] = threadPool.submit(new MyCallable(start, end));

            sum += futures[i].get();
        }

        threadPool.shutdown();
        System.out.println("result -> " + sum);
    }

}